/**
 * @file 公共title
 * @author wl
 * @date 20200311
 */
import React, {useEffect, useState, useRef, useReducer} from 'react';
import {Button} from 'antd';
import {queryCarouselMessage} from '~/service/refundReport';
import './index.less';

const defalutState = {
    // 后端返回的hidden，清楚页面同时清楚计时器
    hidden: 1,
    // pageVisible 是本地状态，控制页面是否展示。计时器的请求还在继续
    pageVisible: true,
    message: ''
};

const reducer = (state, action) => ({...state, ...action});

const CarouselEle = props => {
    const timerRef = useRef();
    const [state, dispatch] = useReducer(reducer, defalutState);
    const {hidden, message, pageVisible} = state;

    const getMessage = () => {
        queryCarouselMessage()
            .then(res => {
                const {text, hidden} = res?.data || {};

                dispatch({
                    hidden,
                    message: text,
                });
            });
    };

    useEffect(() => {
        const asyncFn = async () => {
            const {data} =  await queryCarouselMessage();
            const {text, hidden} = data;

            dispatch({
                message: text,
                hidden
            });

            // const delay = 5 * 60 * 1000;
            // 续班期间 30s 一次
            const delay = 30000;
            timerRef.current = setInterval(() => {
                getMessage();
            }, delay);
        };

        asyncFn(state);

        return () => {
            clearInterval(timerRef.current);
        };
    }, []);

    useEffect(() => {
        dispatch({
            pageVisible: true
        });
    }, [message]);

    const handleClose = () => {
        dispatch({
            pageVisible: false
        });
    };

    if (!hidden) {
        clearInterval(timerRef.current);
        return null;
    }

    return (
        pageVisible && (
            <div className="custom-carousel">
                <Button className="close-btn" type="link" onClick={handleClose}>x</Button>
                <div className="carousel-container">
                    <p className="carousel-content">
                        {/* 防止文字太短，一行轮播展示不全 */}
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        {message}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </p>
                </div>
            </div>
        )
    );
};

export default CarouselEle;
